import { request } from "../../request/index.js";
import regeneratorRuntime, { async } from '../../lib/runtime/runtime';

// pages/user/index.js
Page({

  data: {
    // 是否登录
    isLogin: false,
    // 头像
    avatar: '',
    username: '',
    userType: 0
  },
  
  // 监听页面显示
  onShow () {
    this.isLogin ()
  },

  // 跳转登录页面
  goToLogin () {
    wx.navigateTo({
        url: '/pages/login/index'
    });
  },

  // 是否登录
  async isLogin () {
    if (wx.getStorageSync("token")) {
      const res = await request({
        url: '/user/queryUserByToken',
        method: 'post',
        header: {
          'content-type':'application/json',
          token: wx.getStorageSync('token')
        },
        data: wx.getStorageSync('token')
      })
      if (res.resultTypeCode == 200) {
        const {userName, userType, avatar} = res.data 
        this.setData ({
          isLogin: true,
          userName,
          userType,
          avatar
        })
      }
    } else {
      this.setData ({
        isLogin: false
      })
    }
  },

  // 退出登录
  logout () {
    wx.showModal({
      title: '退出登录？',
      showCancel: true,
      cancelText: '取消',
      cancelColor: '#000000',
      confirmText: '确定',
      confirmColor: '#3CC51F',
      success: (result) => {
        if (!result.confirm) return
        wx.removeStorageSync("token")
        wx.removeStorageSync("DDL")
        wx.showToast({
          title: '已退出登录',
          icon: 'success',
          duration: 1000,
        });
        this.setData ({
          isLogin: false
        })
      }
    });
  }
})